// pages/carDetail/carDetail.js
var app = getApp();
var main = require('../../utils/main.js');
var model = require('../../utils/model/model.js');
var util = require('../../utils/util.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    httpApiImg: app.globalData.httpApiImg,
    isDetail: true,
    userInfo: '',
    imageUrl: app.globalData.imageUrl,
    reply: '',
    isAdd: true,
    inputFocus: false,
    isMine: true,
    showSelect: false,
    page: 1,
    replyObj: {},
    modelData: {
      showModal: false,
      cancelText: '取消',
      confirmText: "确定",
      content: '交易双方都需要支付20%的 保证金，交易完成后资金会 自动返还到您的账户！',
      confirmCallback: 'confirmCallback'
    },
    // modelData: {
    //   showModal: false,
    //   signle: true,
    //   signleBtnTxt: '确定',
    //   content: '交易双方都需要支付20%的 保证金，交易完成后资金会 自动返还到您的账户！',
    // },
    replyList: [],
    carDetail: {},
    loadMoreTxt: '正在加载数据。。。',
    loadMore: false,
    hasData: true,
    hiddenmodalput: true,
    peopelNum: '',
    showModalCode: true,
    modelTitle: '',
    showBtn: true,
    contactNum: '',
    isMinePublish: false,
    loadSuccess:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.showLoading();
    if (wx.getStorageSync('userInfo')) {
      this.setData({
        userInfo: JSON.parse(wx.getStorageSync('userInfo'))
      })
      model.init.apply(this, ['modelData']);
      var that = this;
      var isMine = options.isMine == 'true' ? true : false;

      // if (options.isOrder) {
      //   that.setData({
      //     isOrder: true,
      //     showBtn: false,
      //   })
      // }
      if (options.contactNum) {
        that.setData({
          contactNum: options.contactNum
        })
      }
      if (options.id) {
        this.getDetail(options.id);
      }
      this.setData({
        isMine: isMine
      })
      main.changeInput.apply(this, []);
    } else {
      wx.showModal({
        title: '提示',
        content: '你还没有登录，请登录',
        success: function (res) {
          if (res.confirm) {
            wx.navigateTo({
              url: "/pages/login/login"
            })
          } else {//取消
          }
        }
      })
    }
  },
  getDetail: function (id) {
    var obj = { '1': '车找人', '2': '人找车', '3': '货找车', '4': '车找货' };
    var that = this;
    wx.request({
      url: app.globalData.httpApiCar + 'freeRideInfo/getFreeRideInfo', //仅为示例，并非真实的接口地址
      data: {
        id: id,
        userId: this.data.userInfo.id
      },
      success: function (res) {
        wx.hideLoading();
        that.setData({
          loadSuccess: true
        })
        if (res.data.success) {
          var item = res.data.data;
          wx.setNavigationBarTitle({
            title: obj[item.type + ''],
          })
          item.isStart = false;//未出发
          if (new Date().getTime() > new Date(item.backupA.replace(/-/g, "/")).getTime()) {
            item.isStart = true;
          }
          // if (that.data.isOrder) {
          //   item.contactNum = that.data.contactNum;
          // }
          if (that.data.contactNum) {
            item.contactNum = that.data.contactNum;
          }
          if (item.createTime) {
            item.time = util.getDays(item.createTime)
          }
          if (item.labelArray != undefined && item.labelArray != '') {
            item.mark = item.labelArray.split('/');
          } else {
            item.mark = [];
          }
          that.setData({
            carDetail: item,
            replyList: []
          })
          var userid = that.data.carDetail.userId;
          if (that.data.userInfo.id == userid) {
            that.setData({
              // showBtn: false,
              isMinePublish: true
            })
          };
          that.setData({
            carDetail: item
          });
          that.getLeaveMes();
        }
      }
    })
  },
  getLeaveMes(flag) {//获取留言数据
    var _this = this;
    var param = { type: 1, infoId: this.data.carDetail.id };
    if (!this.data.isMinePublish) {
      param.userId = this.data.userInfo.id;
      param.otherSideId = this.data.carDetail.tGyUserInfo.id;
    }
    wx.request({
      url: app.globalData.httpApiCar + 'messageInfo/all', //仅为示例，并非真实的接口地址
      data: param,
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        wx.hideNavigationBarLoading() //完成停止加载
        wx.stopPullDownRefresh() //停止下拉刷新
        var obj = {};
        res.data.data.forEach(function (ele) {
          ele.time = '';
          if (ele.createTime) {
            // ele.time = util.getHours(new Date(ele.create_date.replace(/-/g, "/")).getTime());
            ele.time = util.getHours(ele.createTime);
          }
          if (ele.messageInfos.length > 0) {
            ele.messageInfos = ele.messageInfos.reverse();
            ele.messageInfos.forEach(function (item) {
              if (item.createTime) {
                item.time = util.getHours(item.createTime);
              }
            })

          }
        })
        _this.setData({
          replyList: res.data.data
        })
      }
    })
  },
  addLeaveMes() {//留言发送按钮点击事件
    if (this.data.reply != '') {
      var formData = {
        userId: this.data.userInfo.id,
        infoId: this.data.carDetail.id,
        message: this.data.reply,
        otherSideId: this.data.carDetail.tGyUserInfo.id,
        status: 2,
        backupA: this.data.carDetail.tGyUserInfo.id
      };
      if (this.data.isAdd) {
        formData.type = 1;
      } else {
        formData.otherSideId = this.data.replyObj.userId;
        formData.type = 2;
        if (this.data.replyObj.parentId) {
          formData.parentId = this.data.replyObj.parentId;
        } else {
          formData.parentId = this.data.replyObj.id;
        }
      }
      var that = this;
      wx.request({
        url: app.globalData.httpApiCar + 'messageInfo/save', //仅为示例，并非真实的接口地址
        data: formData,
        method: 'POST',
        header: {
          'content-type': 'application/x-www-form-urlencoded' // 默认值
          // 'content-type': 'multipart/form-data' // 默认值
        },
        success: function (res) {
          if (res.data.success) {
            that.setData({
              page: 1,
              reply: '',
              isAdd: true
            })
            that.getLeaveMes(true);
          } 
          else {
            wx.showToast({
              title: res.data.error,
              icon: 'none',
              duration: 2000
            })
          }
        }
      })
    }
  },
  collect: function (e) {//收藏
    var that = this;
    if (that.data.carDetail.isCollection == '0') {
      wx.request({
        url: app.globalData.httpApiCar + 'tGyAttention/save', //仅为示例，并非真实的接口地址
        data: {
          userId: this.data.userInfo.id,
          sourceId: that.data.carDetail.id,
          block: 3
        },
        method: 'POST',
        header: {
          'content-type': 'application/x-www-form-urlencoded' // 默认值
        },
        success: function (res) {
          if (res.data.success) {
            that.setData({
              'carDetail.isCollection': '1'
            })
          }
          else {
            wx.showToast({
              title: res.data.error,
              icon: 'none',
              duration: 2000
            })
          }
        }
      })
    } else {
      wx.request({
        url: app.globalData.httpApiCar + 'tGyAttention/deleteAttentionRecordByParams', //仅为示例，并非真实的接口地址
        data: {
          userId: this.data.userInfo.id,
          sourceId: that.data.carDetail.id,
          block: 3
        },
        method: 'POST',
        header: {
          'content-type': 'application/x-www-form-urlencoded' // 默认值
        },
        success: function (res) {
          if (res.data.success) {
            that.setData({
              'carDetail.isCollection': '0'
            })
          }
          else {
            wx.showToast({
              title: res.data.error,
              icon: 'none',
              duration: 2000
            })
          }
        }
      })
    }
  },
  inputBlur: function (e) {
    this.setData({
      isAdd: true,
      reply: ''
    })
  },
  // 回复按钮点击事件
  reply: function (e) {
    this.data.replyObj = e.currentTarget.dataset.item;
    this.data.replyObj.index = e.currentTarget.dataset.index;
    this.setData({
      isAdd: false,
      inputFocus: true,
      replyObj: this.data.replyObj,
      reply: ''
    })
  },
  // tab也切换
  tanSwitch: function (e) {
    var isDetail = e.target.dataset.value == "true" ? true : false;
    this.setData({
      isDetail: isDetail
    })
    this.inputBlur();
  },
  orderTaking: function (e) {//接单 
    var that = this;
    var param = {
      carOrderId: this.data.carDetail.id,
      type: this.data.carDetail.type
    };
    if (this.data.carDetail.type == 2 || this.data.carDetail.type == 3) {
      param.masterId = this.data.userInfo.id;//收款方id
      param.guestId = this.data.carDetail.userId;//付款方id
    } else {
      param.masterId = this.data.carDetail.userId;//收款方id
      param.guestId = this.data.userInfo.id;//付款方id
    }
    if (this.data.carDetail.type == 1) {
      param.freeNum = this.data.peopelNum;
    }
    if (that.data.type == 1 || that.data.type == 4) {
      wx.showModal({
        title: '提示',
        content: '需要支付20%的保证金，确定预约吗？',
        success: function (res) {
          if (res.confirm) {
            that.pulish(param);
          }
        }
      })
    } else {
      that.pulish(param);
    }
  },
  pulish: function (param) {
    var that = this;
    wx.request({
      url: app.globalData.httpApiCar + 'freeRidePay/save', //仅为示例，并非真实的接口地址
      data: param,
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      success: function (res) {
        if (res.data.success) {
          if (that.data.carDetail.type == 1 || that.data.carDetail.type == 4) {
            that.payMoney(res.data.data);
          } else {
            wx.setStorage({
              key: 'url',
              data: '/pages/carMine/carMine'
            })
            wx.redirectTo({
              url: '/pages/regsuccess/regsuccess?showText=接单成功&btnText=查看待收款'
            })
          }
        } else {
          wx.showModal({
            title: '提示',
            content: res.data.error,
            showCancel: false,
            success: function (res) {
              if (res.confirm) {
              }
            }
          })
        }
      }
    })
  },
  payMoney: function (item) {
    var that = this;
    var backupD=2;
    if (this.data.carDetail.type == 2 || this.data.carDetail.type==3){
      backupD=3;
    }
    wx.request({
      url: app.globalData.httpApiCar + 'freeRidePay/reservationOrReceiptMarginPayment', //仅为示例，并非真实的接口地址
      data: {
        openId: app.globalData.openId,
        type: 1,
        backupA: item.backupD,
        backupB: item.id,
        backupC: this.data.carDetail.type,
        backupD: backupD,
        adds: 2,
        userId: this.data.userInfo.id,
        body: '顺风车预约保证金'
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      success: function (res) {
        if (res.data.success) {
          that.requestPayment(res.data.data);
        } else {
          // that.setData({
          //   'modelData.showModal': true,
          //   'modelData.content': '发布失败',
          //   canSubmit: true
          // });
        }
      }
    })
  },
  requestPayment: function (obj) {
    var that = this;
    wx.requestPayment({
      'timeStamp': obj.timeStamp,
      'nonceStr': obj.nonceStr,
      'package': obj.package,
      'signType': obj.signType,
      'paySign': obj.paySign,
      'success': function (res) {
        wx.setStorage({
          key: 'url',
          data: '/pages/carMine/carMine'
        })
        wx.redirectTo({
          url: '/pages/regsuccess/regsuccess?showText=预约成功&btnText=查看待付款'
        })
        // that.payMoney(res.data.data);
      },
      'fail': function (res) {
        wx.showModal({
          title: '提示',
          content: '支付失败',
          showCancel: false,
          success: function (res) {
            if (res.confirm) {
            }
          }
        })
      }
    })
  },
  attestation: function () {
    var flag = true;
    var that = this;
    if (this.data.userInfo.brandCar) {
      this.orderTaking();
    } else {
      flag = false;
      wx.showModal({
        title: '提示',
        content: '你还没有完善车辆信息，请先去完善',
        success: function (res) {
          if (res.confirm) {
            wx.navigateTo({
              url: "/pages/perfectInfo/perfectInfo"
            })
          } else {//取消
          }
        }
      })
    }
    return flag;
  },
  onlineBooking: function () {//在线预约
    var flag=true;
    if (this.data.isMinePublish){
      flag=false;
    }else{
      // if (this.data.carDetail.orderStatus == 1) {
        if (this.data.carDetail.makeAnAppointment == '1') {
          flag = false;
        }
      // }
    }
    
    if (!flag) {
      this.cancelTrip();
    } else {
      var modelTitle = '';
      var flag = true;
      if (this.data.carDetail.type == 1) {
        modelTitle = '请输入人数';
        this.setData({
          hiddenmodalput: !this.data.hiddenmodalput,
          peopelNum: '',
          modelTitle: modelTitle
        })
      } else {
        this.orderTaking();
      }
    }
  },
  //取消按钮  
  cancel: function () {
    this.setData({
      hiddenmodalput: true
    });
  },
  //确认  
  confirm: function () {
    if (this.data.peopelNum != '') {
      if (this.data.peopelNum == 0) {
        wx.showModal({
          title: '提示',
          content: '输入无效！',
          showCancel: false,
          success: function (res) {
            if (res.confirm) {
            }
          }
        })
      } else {
        if (this.data.carDetail.type == 1) {
          var num = this.data.carDetail.goNumSy;
          if (this.data.peopelNum <= num) {
            this.orderTaking();
            this.setData({
              hiddenmodalput: true
            })
          } else {
            wx.showModal({
              title: '提示',
              content: '人数超过可预约的数量',
              showCancel: false,
              success: function (res) {
                if (res.confirm) {
                }
              }
            })
          }
        }
      }
    }
  },
  // 行程结束
  endTrip: function (e) {
    this.setData({
      'modelData.showModal': true,
      'modelData.content': '您的此次行程已经结束，是否支付剩余费用？'
    })
  },
  // 评价
  evalute: function (e) {
    wx.navigateTo({
      url: '/pages/evaluate/evaluate'
    })
  },
  callPhone: function (e) {
    wx.makePhoneCall({
      phoneNumber: this.data.carDetail.contactNum //仅为示例，并非真实的电话号码
    })
    this.setData({
      showSelect: false
    })
  },
  toggleSelect: function (e) {//电话联系
    if (this.data.carDetail.contactNum) {
      var show = e.currentTarget.dataset.value == "true" ? true : false;
      this.setData({
        showSelect: show
      })
    } else {
      this.setData({
        'modelData.showModal': true,
        'modelData.content': '该条发布没有手机号！'
      })
    }

  },
  //取消行程
  cancelTrip: function (e) {
    // ele.time = util.getHours(new Date(ele.create_date.replace(/-/g, "/")).getTime());
    var timerToday = new Date().getTime();
    var begin = new Date(this.data.carDetail.backupA.replace(/-/g, "/")).getTime();
    var hourNum = (begin - timerToday) / 1000 / 60 / 60;
    if (hourNum < 24 && hourNum>=0){
      if (this.data.carDetail.type == 1 || this.data.carDetail.type == 4){
        this.setData({
          'modelData.showModal': true,
          // 'modelData.title': '您单方面的取消行程，将扣除之前预付的20',
          'modelData.content': '离发车不足24小时取消行程将 扣除预付款并赔偿给对方 确定取消吗？'
        })
      }else{
        this.setData({
          'modelData.showModal': true,
          'modelData.content': '确定取消行程吗？'
        })
      }
    }else{
      this.setData({
        'modelData.showModal': true,
        'modelData.content': '确定取消行程吗？'
      })
    }
  },
  confirmCallback:function(){
    var that=this;
    var url='';
    var param={};
    if (this.data.userInfo.id == this.data.carDetail.userId) {
      param.id = this.data.carDetail.id;
      if (this.data.carDetail.type == 1 || this.data.carDetail.type == 4) {//乘客取消
        url = 'freeRideInfo/driverCancelTravel';
      } else {
        url = "freeRideInfo/passengersCancelTravel";
      }
    } else {
      param.id = this.data.carDetail.freeRidePay.id;
      if (this.data.carDetail.type == 1 || this.data.carDetail.type == 4) {//乘客取消
        url = 'freeRidePay/passengersCancelTravel';
      } else {
        url = "freeRidePay/driverCancelTravel";
      }
    }
    wx.request({
      url: app.globalData.httpApiCar + url, //仅为示例，并非真实的接口地址
      data: param,
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      success: function (res) {
        if (res.data.success) {
          wx.showModal({
            title: '提示',
            content: '取消成功',
            showCancel: false,
            success: function (res) {
              if (res.confirm) {
                that.getDetail(that.data.carDetail.id);
              }
            }
          })
        } else {
          wx.showModal({
            title: '提示',
            content: res.data.error,
            showCancel: false,
            success: function (res) {
              if (res.confirm) {
              }
            }
          })
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    wx.removeStorage({
      key: 'carDetail',
      success: function (res) { }
    })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    if (!this.data.isMine) {
      wx.showNavigationBarLoading(); //在标题栏中显示加载
      this.setData({
        page: 1
      })
      this.getLeaveMes(true);
    }
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    // var that = this;
    // if (that.data.hasData) {
    //   this.setData({
    //     loadMoreTxt: '正在加载数据。。。',
    //     loadMore: true,
    //     page: this.data.page + 1
    //   });
    //   this.getLeaveMes();
    // }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (options) {
   
  }
})